package com.ww.springboot.boot.util.pdf;

import cn.hutool.http.HttpRequest;
import com.ww.springboot.boot.utils.Func;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.PDFTextStripperByArea;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ReadPdf {

    public static void main(String[] args) {

        String ss = "JM2215001288008784";



        List<String> list = new ArrayList<>();
        Func.toStrList(ss).forEach(s -> {
            String url = "https://bullfrog-master.oss-cn-shenzhen.aliyuncs.com/delivery_label/" + s + ".pdf";

            byte[] bytes = HttpRequest.get(url).execute().bodyBytes();

            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

            if(!readByStream(inputStream,s)){
                list.add(s);
            }
        });

        System.out.println("-----------------异常订单------------");
        System.out.println(list);

//        byte[] bytes =  HttpRequest.get("http://bullfrog-master.oss-cn-shenzhen.aliyuncs.com/delivery_label/13241000007000613959611001.pdf").execute().bodyBytes();
//
//        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

//        try (PDDocument document = PDDocument.load(new File("C:\\Users\\ZH500\\桌面\\学习\\路人甲Java\\Spring系列【公众号：路人甲Java】(上).pdf"))) {
//
//            document.getClass();
//
//            if (!document.isEncrypted()) {
//
//                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
//
//                stripper.setSortByPosition(true);
//
//                PDFTextStripper tStripper = new PDFTextStripper();
//
//                String pdfFileInText = tStripper.getText(document);
//
//                String lines[] = pdfFileInText.split("\\r?\\n");
//
//                for (String line : lines) {
//
//                    System.out.println("内容:" + line);
//
//                }
//
//            }
//
//        }

    }

    private static Boolean readByStream(ByteArrayInputStream inputStream,String code) {
        try (PDDocument document = PDDocument.load(inputStream)) {

            document.getClass();

            if (!document.isEncrypted()) {

                PDFTextStripperByArea stripper = new PDFTextStripperByArea();

                stripper.setSortByPosition(true);

                PDFTextStripper tStripper = new PDFTextStripper();

                String pdfFileInText = tStripper.getText(document);

                String lines[] = pdfFileInText.split("\\r?\\n");

                for (String line : lines) {
                    System.out.println(line);
                    if(line.contains(code)){
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}